(in-package #:srfi.setagaya)

(export 'cond-61)

(defmacro cond-61 (&body forms)
  (if (every #'null (mapcar (lambda (form) (member '=> form :test #'eq)) forms))
      `(cl:cond ,@forms)		;Basic
      (let (retforms gss)
	(dolist (f forms `(let ,gss (cond ,@(nreverse retforms))))
	  (if (member '=> f :test #'eq)
	      (cl:cond ((and (eq '=> (third f)) (= 4 (list-length f))) ;SRFI-61
			(destructuring-bind (generator guard => receiver) f
			  (declare (ignore =>))
			  (let ((gs (gensym)))
			    (push `((multiple-value-call 
					,guard (values-list 
						(setq ,gs (multiple-value-list 
							   ,generator))))
				    (multiple-value-call ,receiver (values-list ,gs)))
				  retforms)
			    (push `((values-list ,gs)) retforms) ;fall thru
			    (push gs gss))))
		       ((and (eq '=> (second f)) (= 3 (list-length f)))	; R5RS
			(destructuring-bind (generator => receiver) f
			  (declare (ignore =>))
			  (let ((gs (gensym)))
			    (push `((setq ,gs ,generator) (funcall ,receiver ,gs)) retforms))))
		       ('T (error "srfi:COND: bad clause in cond?: ~S" f)))
	      (push f retforms))))))